package com.joey.cloud.flowable.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.joey.cloud.flowable.acthi.entity.ActHiComment;
import com.joey.cloud.flowable.acthi.mapper.ActHiCommentMapper;
import com.joey.cloud.flowable.vo.TaskCommentVo;
import org.flowable.common.engine.impl.identity.Authentication;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.runtime.Execution;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class FlowTaskService {
    //操作任务相关的
    @Autowired
    TaskService taskService;
    //查询历史表数据的
    @Resource
    HistoryService historyService;
    @Resource
    RuntimeService runtimeService;
    @Resource
    ActHiCommentMapper actHiCommentMapper;
    @Resource
    FlowUserService flowUserService;


    /**
     * 获取代办审批意见
     * @param taskId
     * @return
     */
    public TaskCommentVo getCommentVo(String taskId){
        QueryWrapper qw = new QueryWrapper();
        qw.eq("TASK_ID_",taskId);
        List<ActHiComment> list = actHiCommentMapper.selectList(qw);
        TaskCommentVo vo = new TaskCommentVo();
        for(ActHiComment item : list){
            if("taskMessage".equals(item.getType())){
                vo.setTaskMessage(item.getMessage());
            }else if("taskStatus".equals(item.getType())){
                vo.setTaskStatus(item.getMessage());
            }else if("taskComment".equals(item.getType())){
                vo.setTaskComment(item.getMessage());
            }
            vo.setCreateTime(item.getTime());
        }
        return vo;
    }
    /**
     * 跳转流程
     * @param processInstanceId
     * @param targetExecutionId
     * @param taskStatus
     * @param comment
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class)
    public void jumpTask(String processInstanceId,String targetExecutionId,String taskStatus,String comment){

        List<String> currentExecutionIds = new ArrayList<>();
        List<String> taskIds = new ArrayList<>();
        List<Execution> list = runtimeService.createExecutionQuery().parentId(processInstanceId).list();
        if(list==null||list.size()==0){
            return;
        }
        for(Execution exe : list){
            currentExecutionIds.add(exe.getId());
            Task task = taskService.createTaskQuery().executionId(exe.getId()).singleResult();
            if(task!=null&&!taskIds.contains(task.getId())){
                taskIds.add(task.getId());
            }
        }
        String taskMessage = "";
        if("reject".equals(taskStatus)){
            taskMessage = "已驳回";
        }else if("return".equals(taskStatus)){
            taskMessage = "已退回";
        }else {
            taskMessage = "已干预";
            taskStatus = "meddle";
        }
        Authentication.setAuthenticatedUserId(flowUserService.getCurrentUserId());
        for(String taskId:taskIds){
            taskService.addComment(taskId,processInstanceId,"taskStatus",taskStatus);
            taskService.addComment(taskId,processInstanceId,"taskMessage",taskMessage);
            taskService.addComment(taskId,processInstanceId,"taskComment",comment);
        }
        runtimeService.createChangeActivityStateBuilder()
                .moveExecutionsToSingleActivityId(currentExecutionIds,targetExecutionId)
                .changeState();
    }
    /**
     * 审批流程
     * @param task
     * @param comment
     * @param param
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class)
    public void applyTask(Task task, String comment, HashMap<String, Object> param){
        Authentication.setAuthenticatedUserId(flowUserService.getCurrentUserId());
        taskService.addComment(task.getId(),task.getProcessInstanceId(),"taskStatus","success");
        taskService.addComment(task.getId(),task.getProcessInstanceId(),"taskMessage","通过");
        taskService.addComment(task.getId(),task.getProcessInstanceId(),"taskComment",comment);
        taskService.complete(task.getId(), param);
    }

    /**
     * 通过任务id获取任务
     * @param taskId
     * @return
     */
    public Task getById(String taskId){
        return taskService.createTaskQuery().taskId(taskId).singleResult();
    }


}
